﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Configuration;

namespace CookieFreeAnalytics
{
    public static class CFAGlobal
    {
        // Store all the settings in static variables to save look up from web.config

        // Our various filters to clean up the data
        static public bool EnableIPFilter { get; set; }// Flag for setting IP filter
        static public bool EnableFolderFilter { get; set; }// Folder filter
        static public bool EnableGIFTracking { get; set; }// Return GIF requests
        static public bool EnableTracking { get; set; }// flag for enabling tracking of pages
        static public bool EnableEvents { get; set; }// Flag for enabling tracking of events
        static public bool EnableSQL { get; set; } // Enable SQL support
        static public bool EnableMonitoringFilter { get; set; } // Enable SQL support
        static public bool EnableAllowForwardSlash { get; set; } // Enable SQL support
        static public bool EnableEatGACookieRtnVisit { get; set; } // Use existing GA cookie for return visitors
        static public bool EnableExtensionlessURLs { get; set; } // Use extenionless urls

        static public string PropertyID { get; set; }// GA Property ID. In MO- format (Is MO still required?)
        static public bool debugenabled { get; set; }// Enable rough debug strings
        static public string ipfilter { get; set; }// Single IP address filter (Needs to be upgraded to RegEx for Pro version)

        static public string trackextensions { get; set; } // Extensions to report as page views
        static public string eventextensions { get; set; } // Extensions to report as events // NOT YET IMPLEMENTED
        static public string filterFolders { get; set; } // Folders / files to be filtered. Usually with leading and trailing slash, can work without
        static public string monitoringFilter { get; set; } // Folders / files to be filtered. Usually with leading and trailing slash, can work without

        // For SQL Access
        static public string platformReference { get; set; } // Set to SQL
        static public string platformQueryStringKey { get; set; } // Key name
        static public string platformQueryStringKeyFormat { get; set; } // int or guid
        static public string tableName { get; set; } // SQL Table name
        static public string IDfield { get; set; } // SQL Field ID
        static public string URLField { get; set; } // SQL URL field name
        static public string OrderByField { get; set; } // Order by ... desc

        // Arrays for web config keys
        static public string[] filterFoldersArr;
        static public string[] allowedTracking;
        static public string[] allowedEvents;
        static public string[] filterUserAgents;

        // Added V1.0.0.2 //
        static public bool EnableExporting { get; set; }// Enable exporting of GA requests to CookieFree "Collector" web site
        static public bool EnableCollectionMode { get; set; } // Enable Colllection Mode - will track all activity, be it spider / human. Requires EnableExporting to be enabled
        static public string exportURL { get; set; } // Full URL of "Collector" website, ie http://collector.cookiefreeanalytics.co.uk/collect.aspx 



        static CFAGlobal()
        {


            EnableSQL = true; // Set true until settings read.

            // Property ID. Only real setting thats needed
            if (System.Configuration.ConfigurationManager.AppSettings["CookieFreePropertyID"] != null)
            {
                PropertyID = System.Configuration.ConfigurationManager.AppSettings["CookieFreePropertyID"];
            }

            // Debug Output. Not useful results yet.
            if (System.Configuration.ConfigurationManager.AppSettings["CookieFreeDebugEnable"] != null)
            {
                try
                {
                    debugenabled = Boolean.Parse(System.Configuration.ConfigurationManager.AppSettings["CookieFreeDebugEnable"].ToString());
                }
                catch (Exception)
                {
                    debugenabled = false;
                }

            }

            // Debug Output. Not useful results yet.
            if (System.Configuration.ConfigurationManager.AppSettings["CookieFreeExtensionlessURLs"] != null)
            {
                try
                {
                    EnableExtensionlessURLs = Boolean.Parse(System.Configuration.ConfigurationManager.AppSettings["CookieFreeExtensionlessURLs"].ToString());
                }
                catch (Exception)
                {
                    EnableExtensionlessURLs = false;
                }

            }


            // Enable GIF Tracking Only
            if (System.Configuration.ConfigurationManager.AppSettings["CookieFreeGIFEnable"] != null)
            {
                try
                {
                    EnableGIFTracking = bool.Parse(System.Configuration.ConfigurationManager.AppSettings["CookieFreeGIFEnable"].ToString());
                }
                catch (Exception)
                {
                    EnableGIFTracking = false;
                }

            }

            // Folder Filter. Folders to not report on
            if (System.Configuration.ConfigurationManager.AppSettings["CookieFreeFilterFolders"] != null)
            {
                filterFolders = System.Configuration.ConfigurationManager.AppSettings["CookieFreeFilterFolders"].ToString();
                if (filterFolders.Length > 0)
                {
                    filterFoldersArr = filterFolders.TrimEnd('|').Split('|');
                    //Array.ConvertAll<string, string>(filterFoldersArr, delegate(string s) { return s.ToLower(); });
                    EnableFolderFilter = true;
                }
                else
                {
                    EnableFolderFilter = false;
                }

            }
            else
            {
                EnableFolderFilter = false;
            }

            // File extension to report page views on
            if (System.Configuration.ConfigurationManager.AppSettings["CookieFreeTrackExtensions"] != null)
            {
                trackextensions = System.Configuration.ConfigurationManager.AppSettings["CookieFreeTrackExtensions"].ToString();
                if (trackextensions.Length > 0)
                {
                    allowedTracking = trackextensions.TrimEnd('|').Split('|');
                    //string[] temparr = Array.ConvertAll<string, string>(allowedTracking, delegate(string s) { return s.ToLower(); });
                    //allowedEvents = temparr;
                    //temparr = null;
                    EnableTracking = true;
                }
                else
                {
                    SetDefaultTracking();
                }
            }
            else
            {
                SetDefaultTracking();

            }


            // File extension to report Events on
            if (System.Configuration.ConfigurationManager.AppSettings["CookieFreeEventExtensions"] != null)
            {
                eventextensions = System.Configuration.ConfigurationManager.AppSettings["CookieFreeEventExtensions"].ToString();
                if (eventextensions.Length > 0)
                {
                    allowedEvents = eventextensions.TrimEnd('|').Split('|');
                    //string[] temparr =  Array.ConvertAll<string, string>(allowedEvents, delegate(string s) { return s.ToLower(); });
                    //allowedEvents = temparr;
                    //temparr = null;
                    EnableEvents = true;
                }
                else
                {
                    EnableEvents = false;
                    SetDefaultEvents();
                }
            }
            else
            {
                EnableEvents = false;
                SetDefaultEvents();
            }



            // IP Filter. Might swap to Regex in future for IP ranges.
            if (System.Configuration.ConfigurationManager.AppSettings["CookieFreeBlockSingleIP"] != null)
            {
                ipfilter = System.Configuration.ConfigurationManager.AppSettings["CookieFreeBlockSingleIP"].ToString();
                if (ipfilter.Length > 0) EnableIPFilter = true;
            }


            // Partial User Agent String. 
            if (System.Configuration.ConfigurationManager.AppSettings["CookieFreeSiteMonitoringUAFilter"] != null)
            {
                monitoringFilter = System.Configuration.ConfigurationManager.AppSettings["CookieFreeSiteMonitoringUAFilter"].ToString();
                if (monitoringFilter.Length > 0)
                {
                    filterUserAgents = monitoringFilter.TrimEnd('|').Split('|');
                    //Array.ConvertAll<string, string>(filterUserAgents, delegate(string s) { return s.ToLower(); });
                    EnableMonitoringFilter = true;
                }
                else
                {
                    EnableMonitoringFilter = false;

                }
            }
            else
            {
                EnableMonitoringFilter = false;
            }

            // Enable tracking of forward slash
            if (System.Configuration.ConfigurationManager.AppSettings["CookieFreeSiteAllowForwardSlash"] != null)
            {
                try
                {
                    EnableAllowForwardSlash = bool.Parse(System.Configuration.ConfigurationManager.AppSettings["CookieFreeSiteAllowForwardSlash"].ToString());
                }
                catch (Exception)
                {
                    EnableAllowForwardSlash = false;
                }

            }
            else
            {
                EnableAllowForwardSlash = false;
            }

            // Consume GA Cookie for return visitors
            if (System.Configuration.ConfigurationManager.AppSettings["CookieFreeSiteEatGACookieReturnVisitor"] != null)
            {
                try
                {
                    EnableEatGACookieRtnVisit = bool.Parse(System.Configuration.ConfigurationManager.AppSettings["CookieFreeSiteEatGACookieReturnVisitor"].ToString());
                }
                catch (Exception)
                {
                    EnableEatGACookieRtnVisit = false;
                }
            }
            else
            {
                EnableEatGACookieRtnVisit = false;
            }

            // V1.0.0.2
            #region Version1.0.0.2
            // Check for exportURL
            if (System.Configuration.ConfigurationManager.AppSettings["CookieFreeCollectorURL"] != null)
            {
                try
                {
                    exportURL = System.Configuration.ConfigurationManager.AppSettings["CookieFreeCollectorURL"].ToString();
                    EnableExporting = true;
                }
                catch (Exception)
                {
                    EnableExporting = false;
                }
            }
            else
            {
                EnableExporting = false;
            }


            // Check for Collection mode.
            // If Collection mode is enabled we will track a spider activity and send it to the CollectionURL.
            // This is so the CFA core can be reused for another pet project.
            if (System.Configuration.ConfigurationManager.AppSettings["CookieFreeCollectionMode"] != null)
            {
                try
                {
                    string tmpCollectionOnly;
                    tmpCollectionOnly = System.Configuration.ConfigurationManager.AppSettings["CookieFreeCollectionMode"].ToString();
                    EnableCollectionMode = true;
                }
                catch (Exception)
                {
                    EnableCollectionMode = false;
                }
            }
            else
            {
                EnableCollectionMode = false;
            }
            #endregion



            // #####################################
            // Used for SQL Access
            // #####################################
            #region SQL
            // If we have a platform reference then load additional keys
            if (System.Configuration.ConfigurationManager.AppSettings["CookieFreePlatformReference"] != null)
            {
                platformReference = System.Configuration.ConfigurationManager.AppSettings["CookieFreePlatformReference"].ToString().ToLower();


                if (System.Configuration.ConfigurationManager.AppSettings["CookieFreePlatformQueryStringKey"] != null)
                {
                    platformQueryStringKey = System.Configuration.ConfigurationManager.AppSettings["CookieFreePlatformQueryStringKey"].ToString();
                }
                else
                {
                    EnableSQL = false;
                }

                // If we say out platform is SQL then load the SQL Keys
                #region SQL Values
                if (platformReference.Contains("sql"))
                {

                    // Database Table Name
                    if (System.Configuration.ConfigurationManager.AppSettings["CookieFreeTableName"] != null)
                    {
                        tableName = System.Configuration.ConfigurationManager.AppSettings["CookieFreeTableName"].ToString();
                    }
                    else
                    {
                        EnableSQL = false;
                    }

                    // Fieldname for page ID
                    if (System.Configuration.ConfigurationManager.AppSettings["CookieFreeIDFieldName"] != null)
                    {
                        IDfield = System.Configuration.ConfigurationManager.AppSettings["CookieFreeIDFieldName"].ToString();
                    }
                    else
                    {
                        EnableSQL = false;
                    }

                    // Fieldname for page url
                    if (System.Configuration.ConfigurationManager.AppSettings["CookieFreeURLFieldName"] != null)
                    {
                        URLField = System.Configuration.ConfigurationManager.AppSettings["CookieFreeURLFieldName"].ToString();
                    }
                    else
                    {
                        EnableSQL = false;
                    }

                    // Fieldname for ordering date created. Incase of multiple urls
                    if (System.Configuration.ConfigurationManager.AppSettings["CookieFreeOrderByFieldName"] != null)
                    {
                        OrderByField = System.Configuration.ConfigurationManager.AppSettings["CookieFreeOrderByFieldName"].ToString();
                    }
                    else
                    {

                    }

                    // Fieldname for ordering date created. Incase of multiple urls
                    if (System.Configuration.ConfigurationManager.AppSettings["CookieFreeIDFieldNameFormat"] != null)
                    {
                        platformQueryStringKeyFormat = System.Configuration.ConfigurationManager.AppSettings["CookieFreeIDFieldNameFormat"].ToString();
                    }
                    else
                    {
                        platformQueryStringKeyFormat = "";
                    }

                }
                #endregion

            }

            #endregion

        }


        public static void SetDefaultTracking()
        {
            trackextensions = ".aspx|.htm|.html";
            allowedTracking = trackextensions.TrimEnd('|').Split('|');
            //Array.ConvertAll<string, string>(allowedTracking, delegate(string s) { return s.ToLower(); });
            EnableTracking = true;
        }


        public static void SetDefaultEvents()
        {
            eventextensions = "";
            allowedEvents = eventextensions.TrimEnd('|').Split('|');
            //Array.ConvertAll<string, string>(allowedEvents, delegate(string s) { return s.ToLower(); });
            EnableEvents = false;
        }

        // Check if folder name is filtered out. Return true if blocked
        public static bool IsFiltered(string fullurl)
        {
            //fullurl = fullurl.ToLower();
            foreach (string s in CFAGlobal.filterFoldersArr)
            {
                if (fullurl.IndexOf(s, 0, StringComparison.CurrentCultureIgnoreCase) > 0) //.Contains(s))
                {
                    return true;
                }
            }
            return false;
        }

        // Check if file extension is tracked as page view
        public static bool IsPageView(string fullurl)
        {
            // If extensionless urls enabled then check for file ext
            if (CFAGlobal.EnableExtensionlessURLs)
            {
                // Working in reverse, if we have a dot less than a forward slash then we have no extension.
                if (fullurl.LastIndexOf(".") < fullurl.LastIndexOf("/"))
                {
                    //CFA_Core.ResponseDebug("Trigger tracking");
                    return true;
                }
            }

            // If an extension has been found, check to see if its on allowed list

            //fullurl = fullurl.ToLower();
            foreach (string s in CFAGlobal.allowedTracking)
            {
                if (fullurl.IndexOf(s, 0, StringComparison.CurrentCultureIgnoreCase) > 0) //.Contains(s))
                {
                    return true;
                }
            }
            if (fullurl.EndsWith("/"))
            {
                return true;
            }

            return false;
        }

        // Check if file extension is tracked as page view
        public static bool IsBlockedAgent(string useragent)
        {
            //useragent = useragent.ToLower();
            foreach (string s in CFAGlobal.filterUserAgents)
            {
                if (useragent.IndexOf(s, 0, StringComparison.CurrentCultureIgnoreCase) > 0) //.Contains(s))
                {
                    return true;
                }
            }

            return false;
        }

        // Check if file extension is tracked as event
        public static bool IsEvent(string fullurl)
        {
            // fullurl = fullurl.ToLower();
            foreach (string s in CFAGlobal.allowedEvents)
            {
                if (fullurl.IndexOf(s, 0, StringComparison.CurrentCultureIgnoreCase) > 0)//.Contains(s))
                {
                    return true;
                }
            }
            return false;
        }
    }
}